package cn.com.callback

import cn.com.elite.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
 *
 * @Title: tab_dyn_page_diy
 * @Description:华盛证券 将 tab_dyn_page 表动态页面的内容 拆分 key + values  --内部接口
 * @author: chieh
 * @date 2022-12-20 10:28:00
 *
 */

public class aipHSTtab_dyn_page_diy implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTtab_dyn_page_diy.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            String PAGEID="";
            String CONTENT="";

            //查询
            List selectbrandList = eliteBean.chaxun_sql("select PAGEID,CONTENT from tab_dyn_page", "dataSource");
            def brandcount = selectbrandList.size();
            log.debug("待处理的数量 brandcount：" + brandcount);
            //判断如待处理的数据数量大于0则执行
            if(brandcount> 0){
                for(int i = 0; i<brandcount; i++) {
                    Map selectbrandMap = selectbrandList.get(i);
                    PAGEID = selectbrandMap.get("PAGEID");//key 动态页面6位id
                    CONTENT = selectbrandMap.get("CONTENT");//动态页面内容
                    //log.debug("PAGEID:" + PAGEID+"	CONTENT:" + CONTENT);

                    //增加异常机制，处置解析不合规的数据则跳出
                    try {
                        def result;
                        JSONObject val = JSONObject.parseObject(CONTENT);

                        //analysis(val);
                        analysis(eliteBean,val,PAGEID);

                    }catch (Exception e) {
                        log.error("跳出下一次,解析异常:" + e.getMessage());
                        continue;
                    }

                }
            }
            outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\"}";
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        //log.debug("更新 信息完成返回结果:" + outData);

        return outData;
    }

    /*
	递归解析JSONObject转换成map
	存在的问题:如果json数据中存在样的key,则后面的值会覆 盖前面的key ???
	@param jsonObject
	@return
	*/
    /*
    public static Map<String,Object> analysis(EliteBean eliteBean,JSONObject jsonObject,String PAGEID){
        Map <String,Object> result = new HashMap<>();
        Set<String> keys = jsonObject.keySet();
        keys.parallelStream().forEach(key->{
            Object value = jsonObject.get(key);
            if(value instanceof JSONObject){
                JSONObject valueJsonObject = (JSONObject) value;
                result.putAll(analysis(valueJsonObject));
            }else if(value instanceof JSONArray){
                JSONArray jsonArray = (JSONArray) value;
                if(jsonArray.size() == 0){
                    return;
                }
                analysisJSONAray(jsonArray,result);
            }else{
                result.put(key,value);
                log.debug(key+":"+ value);
                def dataresult = eliteBean.update("insert into tab_dyn_page_diy(PAGEID,key,value) select '" + PAGEID + "','" + key + "','" + value + "' from dual", "dataSource");
                log.debug("dataresult:" + dataresult);
            }
        });
        return result;
    }
    */
    public static Map<String, Object> analysis(EliteBean eliteBean,JSONObject jsonObject,String PAGEID){
    //public static Map<String, Object> analysis(JSONObject jsonObject){
        Map<String, Object> result = new HashMap<>();
        Set<String> keys = jsonObject.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                JSONObject valueJsonObject = (JSONObject) value;
                //result.putAll(analysis(valueJsonObject));
                result.putAll(analysis(eliteBean,valueJsonObject,PAGEID));
            } else if (value instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) value;
                if (jsonArray.size() == 0) {
                    break;
                }
                //analysisJSONArray(jsonArray, result);
                analysisJSONArray(eliteBean,jsonArray, result,PAGEID);
            } else {
                result.put(key, value);
                //log.debug(key+":"+ value);
                def dataresult = eliteBean.update("insert into tab_dyn_page_diy( PAGEID, key1, value1) VALUES('" + PAGEID + "','" + key + "','" + value + "')", "dataSource");
                //log.debug("dataresult:" + dataresult);
            }
        }
        return result;
    }

    /**
     递归解析JSONArray
     @param jsonArray
     @param map
     */
    /*
   public static void analysisJSONAray(JSONArray jsonArray,Map<String,Object>map) {
       jsonArray.parallelStream().forEach(json->{
       Iterator<String> iterator = keys.iterator();
       while (iterator.hasNext()) {
           String json = iterator.next();
           if(json instanceof JSONObject){
               JSONObject valueJsonObject = (JSONObject) json;
               map.putAll(analysis(valueJsonObject));
           }else if(json instanceof JSONArray){
               JSONArray tmpJsonArray = (JSONArray)json;
               if(tmpJsonArray.size() == 0){
                   return;
               }
               analysisJSONAray(tmpJsonArray,map);
           }
       });
   }
   */
    public static void analysisJSONArray(EliteBean eliteBean,JSONArray jsonArray, Map<String, Object> map,String PAGEID) {
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            Object json = iterator.next();
            if (json instanceof JSONObject) {
                JSONObject valueJsonObject = (JSONObject) json;
                //map.putAll(analysis(valueJsonObject));
                map.putAll(analysis(eliteBean,valueJsonObject,PAGEID));
            } else if (json instanceof JSONArray) {
                JSONArray tmpJsonArray = (JSONArray) json;
                if (tmpJsonArray.size() == 0) {
                    break;
                }
                analysisJSONArray(eliteBean,tmpJsonArray, map,PAGEID);
            }
        }
    }

}
